package com.javarush.test.level26.lesson15.big01;

import com.javarush.test.level26.lesson15.big01.exception.InterruptOperationException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by admin on 08.04.2015.
 */
public class ConsoleHelper {
    private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    public static void writeMessage(String message){
        System.out.println(message);
    }

    public static String readString()  throws InterruptOperationException {
        String result = null;
        try
        {
            result = reader.readLine();
        }
        catch (IOException ignored){}

        if("exit".equalsIgnoreCase(result)){
            throw new InterruptOperationException();
        }
        return result;
    }

    public static String askCurrencyCode() throws InterruptOperationException {
        writeMessage("Input currency code, please...");
        String currencyCode = readString();
        if(currencyCode.length() != 3){
            writeMessage("You put wrong currency code. Please try again.");
            currencyCode = askCurrencyCode();
        }
        return currencyCode.toUpperCase();
    }
    public static String[] getValidTwoDigits(String currencyCode) throws InterruptOperationException {
        writeMessage("Input denomination and amount...");
        String twoDigitsLine = readString();
        String[] digits = twoDigitsLine.split(" ");
        if(digits.length != 2){
            writeMessage("You put wrong denomination and amount. Please try again.");
            digits = getValidTwoDigits(currencyCode);
        }
        int denomination;
        int amount;
        try
        {
            denomination = Integer.parseInt(digits[0]);
            amount = Integer.parseInt(digits[1]);
            if(denomination <= 0 || amount < 0) throw new NumberFormatException();
        }catch (NumberFormatException e){
            writeMessage("You put wrong denomination and amount. Please try again.");
            digits = getValidTwoDigits(currencyCode);
        }
        return digits;
    }

    public static Operation askOperation()  throws InterruptOperationException {
        Operation op=null;
        while(true) {
            writeMessage("Enter operation code:");
            Integer o = Integer.parseInt(readString());
            try {
                op = Operation.getAllowableOperationByOrdinal(o);
                break;
            }catch (IllegalArgumentException e){
                System.out.print("ERROR");
            }
        }
        return op;
    }
}
